package com.core.app.window.view.data;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.dialogs.ConfirmDialog;

import com.core.app.event.CallbackEvent;
import com.core.app.window.view.detail.DetailSekolahView;
import com.core.context.Inject;
import com.core.entity.Sekolah;
import com.core.service.SekolahService;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.Notification;

public class DataSekolahView extends CustomComponent {

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	@AutoGenerated
	private VerticalLayout mainLayout;
	@AutoGenerated
	private Table sekolahTable;
	@AutoGenerated
	private HorizontalLayout horizontalLayout_1;
	@AutoGenerated
	private Button deleteSekolahButton;
	@AutoGenerated
	private Button detailSekolahButton;
	@AutoGenerated
	private Button insertSekolahButton;
	@AutoGenerated
	private ComboBox tingkatanComboBox;

	@Autowired
	private SekolahService sekolahService;

	private BeanContainer<Long, Sekolah> sekolahContainer;

	ClickListener viewDetailSekolahListener = new ClickListener() {

		private static final long serialVersionUID = 8777128358670451625L;

		@Override
		public void buttonClick(ClickEvent event) {
			if (sekolahTable.getValue() != null) {
				Object value = sekolahTable.getValue();
				try {
					Sekolah s = sekolahService.find((Long) value);
					viewDetail(s);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
	};

	private CallbackEvent callbackEvent = new CallbackEvent() {

		@Override
		public void callback(Object object) {
			loadTableSekolah();
		}
	};

	ClickListener newSekolahListener = new ClickListener() {

		private static final long serialVersionUID = 5200747415312589055L;

		@Override
		public void buttonClick(ClickEvent event) {
			newSekolah();
		}
	};

	ClickListener deleteSekolahListener = new ClickListener() {

		@Override
		public void buttonClick(ClickEvent event) {
			deleteSekolah();
		}
	};

	/**
	 * 
	 */
	private static final long serialVersionUID = 7166117189053490233L;

	/**
	 * The constructor should first build the main layout, set the composition
	 * root and then do any custom initialization.
	 * 
	 * The constructor will not be automatically regenerated by the visual
	 * editor.
	 */
	public DataSekolahView() {
		Inject.Inject(this);
		buildMainLayout();
		setCompositionRoot(mainLayout);

		// TODO add user code here

		initTingkatanComboBox();
		tingkatanComboBox.setValue(Sekolah.TK);
		loadTableSekolah();
		insertSekolahButton.addListener(newSekolahListener);
		detailSekolahButton.addListener(viewDetailSekolahListener);
		deleteSekolahButton.addListener(deleteSekolahListener);
	}

	/**
	 * Init tingkatan combobox
	 */
	private void initTingkatanComboBox() {

		tingkatanComboBox.addItem(Sekolah.TK);
		tingkatanComboBox.setItemCaption(Sekolah.TK, Sekolah.TK);
		tingkatanComboBox.addItem(Sekolah.SD);
		tingkatanComboBox.setItemCaption(Sekolah.SD, Sekolah.SD);
		tingkatanComboBox.addItem(Sekolah.SMP);
		tingkatanComboBox.setItemCaption(Sekolah.SMP, Sekolah.SMP);
		tingkatanComboBox.addItem(Sekolah.SMA);
		tingkatanComboBox.setItemCaption(Sekolah.SMA, Sekolah.SMA);
		tingkatanComboBox.setInputPrompt("Pilih Tingkatan Sekolah");
		tingkatanComboBox.setImmediate(true);
		tingkatanComboBox.addListener(new ValueChangeListener() {

			/**
			 * 
			 */
			private static final long serialVersionUID = -2650967229656998192L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				if (tingkatanComboBox.getValue() != null)
					loadTableSekolah();
			}
		});
	}

	/**
	 * Ketika tingkatan yang dipilih berubah, dan menampilkan data sesuai
	 * tingktan yang dipilih
	 */
	private void loadTableSekolah() {

		String tingkatan = (String) tingkatanComboBox.getValue();
		System.out.println(tingkatan);

		sekolahContainer = new BeanContainer<Long, Sekolah>(Sekolah.class);
		sekolahContainer.setBeanIdProperty("id");
		sekolahContainer.addNestedContainerProperty("kecamatan.nama");
		try {
			List<Sekolah> sekolahList = sekolahService.findAllByProperty(
					"tingkatan", tingkatan);
			Collections.sort(sekolahList, new Comparator<Sekolah>() {

				@Override
				public int compare(Sekolah o1, Sekolah o2) {
					// TODO Auto-generated method stub
					return o1.getId().compareTo(o2.getId());
				}
			});
			sekolahContainer.addAll(sekolahList);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		sekolahTable.setContainerDataSource(sekolahContainer);
		sekolahTable.setColumnHeader("nss", "NSS");
		if ("SD".equals(tingkatan) || "TK".equals(tingkatan))
			sekolahTable.setColumnHeader("npsn", "NPSN");
		sekolahTable.setColumnHeader("nama", "Nama");
		sekolahTable.setColumnHeader("akreditasi", "Akreditasi");
		sekolahTable.setColumnHeader("latitude", "Latitude");
		sekolahTable.setColumnHeader("longitude", "Longitude");
		sekolahTable.setColumnHeader("kecamatan.nama", "Kecamatan");

		if ("SD".equals(tingkatan) || "TK".equals(tingkatan))
			sekolahTable.setVisibleColumns(new String[] { "nss", "npsn",
					"nama", "akreditasi", "latitude", "longitude",
					"kecamatan.nama" });
		else {
			sekolahTable.setVisibleColumns(new String[] { "nss", "nama",
					"akreditasi", "latitude", "longitude", "kecamatan.nama" });

		}

		sekolahTable.setSelectable(true);
	}

	private void viewDetail(Sekolah s) throws Exception {
		Window detailSekolahWindow = new Window();
		detailSekolahWindow.setResizable(false);
		detailSekolahWindow.setModal(true);
		if (s.getNama().length() == 0) {
			detailSekolahWindow.setCaption("Insert Data Sekolah");
		}
		detailSekolahWindow.setCaption(s.getNama());
		DetailSekolahView detailSekolahView = new DetailSekolahView(s);
		detailSekolahView.setLoadEvents(callbackEvent);
		detailSekolahView.setTingkatan(s.getTingkatan());
		detailSekolahWindow.setContent(detailSekolahView);
		getApplication().getMainWindow().addWindow(detailSekolahWindow);
	}

	private void newSekolah() {
		Sekolah s = new Sekolah();
		s.setTingkatan(new String((String) tingkatanComboBox.getValue()));
		s.setAkreditasi('-');
		s.setAlamat("");
		s.setLatitude("0");
		s.setLongitude("0");
		s.setNama("");
		s.setNoTelp("");
		s.setNpsn("");
		s.setNss("");
		s.setSiswaSekarang(0);
		s.setSiswiSekarang(0);
		s.setTingkatan("");
		s.setUangGedung(BigDecimal.ZERO);
		s.setUangSpp(BigDecimal.ZERO);
		s.setWebsite("");
		try {
			Window detailSekolahWindow = new Window();
			detailSekolahWindow.setResizable(false);
			detailSekolahWindow.setModal(true);
			if (s.getNama().length() == 0) {
				detailSekolahWindow.setCaption("Insert Data Sekolah");
			}
			detailSekolahWindow.setCaption(s.getNama());
			DetailSekolahView detailSekolahView = new DetailSekolahView(s);
			detailSekolahView.setLoadEvents(callbackEvent);
			detailSekolahView.setTingkatan(new String(
					(String) tingkatanComboBox.getValue()));
			detailSekolahWindow.setContent(detailSekolahView);
			getApplication().getMainWindow().addWindow(detailSekolahWindow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteSekolah() {
		Object value = sekolahTable.getValue();
		try {
			final Sekolah s = sekolahService.find((Long) value);
			ConfirmDialog.show(getWindow(), "Are you sure to delete?",
					new ConfirmDialog.Listener() {

						private static final long serialVersionUID = -5331318794164071160L;

						@Override
						public void onClose(ConfirmDialog dialog) {
							if (dialog.isConfirmed()) {
								try {
									sekolahService.delete(s);
									loadTableSekolah();
								} catch (Exception e) {
									DataSekolahView.this
											.getApplication()
											.getMainWindow()
											.showNotification(
													"Delete failed!",
													e.getMessage(),
													Notification.TYPE_ERROR_MESSAGE);
									e.printStackTrace();
								}
							}

						}
					});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@AutoGenerated
	private VerticalLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new VerticalLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(true);
		mainLayout.setSpacing(true);

		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");

		// horizontalLayout_1
		horizontalLayout_1 = buildHorizontalLayout_1();
		mainLayout.addComponent(horizontalLayout_1);

		// sekolahTable
		sekolahTable = new Table();
		sekolahTable.setImmediate(false);
		sekolahTable.setWidth("100.0%");
		sekolahTable.setHeight("100.0%");
		mainLayout.addComponent(sekolahTable);
		mainLayout.setExpandRatio(sekolahTable, 1.0f);

		return mainLayout;
	}

	@AutoGenerated
	private HorizontalLayout buildHorizontalLayout_1() {
		// common part: create layout
		horizontalLayout_1 = new HorizontalLayout();
		horizontalLayout_1.setImmediate(false);
		horizontalLayout_1.setWidth("-1px");
		horizontalLayout_1.setHeight("-1px");
		horizontalLayout_1.setMargin(false);
		horizontalLayout_1.setSpacing(true);

		// tingkatanComboBox
		tingkatanComboBox = new ComboBox();
		tingkatanComboBox.setImmediate(false);
		tingkatanComboBox.setWidth("-1px");
		tingkatanComboBox.setHeight("-1px");
		horizontalLayout_1.addComponent(tingkatanComboBox);

		// insertSekolahButton
		insertSekolahButton = new Button();
		insertSekolahButton.setCaption("Add");
		insertSekolahButton.setImmediate(false);
		insertSekolahButton.setWidth("75px");
		insertSekolahButton.setHeight("-1px");
		horizontalLayout_1.addComponent(insertSekolahButton);

		// editSekolahButton
		detailSekolahButton = new Button();
		detailSekolahButton.setCaption("Detail");
		detailSekolahButton.setImmediate(false);
		detailSekolahButton.setWidth("75px");
		detailSekolahButton.setHeight("-1px");
		horizontalLayout_1.addComponent(detailSekolahButton);

		// deleteSekolahButton
		deleteSekolahButton = new Button();
		deleteSekolahButton.setCaption("Delete");
		deleteSekolahButton.setImmediate(false);
		deleteSekolahButton.setWidth("75px");
		deleteSekolahButton.setHeight("-1px");
		horizontalLayout_1.addComponent(deleteSekolahButton);

		return horizontalLayout_1;
	}

}
